// ==========================================
// 资产借用管理API - 第二阶段
// ==========================================

// 申请借用资产
app.post('/api/asset/loan/apply', async (req, res) => {
    try {
        const { assetId, purpose, expectedReturnDate } = req.body;
        const { openid, userInfo } = req.body; // 实际应从登录态获取

        if (!assetId || !purpose || !expectedReturnDate) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        // 检查资产是否存在且可借用
        const [assets] = await pool.execute(
            'SELECT * FROM assets WHERE id = ? AND is_loanable = 1',
            [assetId]
        );

        if (assets.length === 0) {
            return res.json({ code: 2001, success: false, message: '资产不存在或不可借用' });
        }

        // 检查资产是否已被借用
        if (assets[0].current_loan_id) {
            return res.json({ code: 2002, success: false, message: '资产已被借用' });
        }

        // 创建借用申请
        const [result] = await pool.execute(
            `INSERT INTO asset_loans (asset_id, borrower_openid, borrower_name, purpose, expected_return_date, status)
             VALUES (?, ?, ?, ?, ?, 'pending')`,
            [assetId, openid, userInfo?.nickName || '用户', purpose, expectedReturnDate]
        );

        res.json({
            code: 0,
            success: true,
            message: '申请成功，等待审批',
            data: { loanId: result.insertId }
        });
    } catch (error) {
        console.error('申请借用失败:', error);
        res.json({ code: 9999, success: false, message: '申请失败' });
    }
});

// 获取借用记录列表
app.get('/api/asset/loans', async (req, res) => {
    try {
        const { status, borrower, assetId, page = 1, pageSize = 20 } = req.query;

        let sql = `SELECT al.*, a.asset_code, a.name as asset_name, a.brand, a.model
                   FROM asset_loans al
                   LEFT JOIN assets a ON al.asset_id = a.id
                   WHERE 1=1`;
        const params = [];

        if (status) {
            sql += ' AND al.status = ?';
            params.push(status);
        }
        if (borrower) {
            sql += ' AND al.borrower_openid = ?';
            params.push(borrower);
        }
        if (assetId) {
            sql += ' AND al.asset_id = ?';
            params.push(assetId);
        }

        sql += ' ORDER BY al.created_at DESC LIMIT ? OFFSET ?';
        params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize));

        const [rows] = await pool.execute(sql, params);

        res.json({ code: 0, success: true, data: { list: rows } });
    } catch (error) {
        console.error('获取借用记录失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 审批借用（管理员）
app.post('/api/admin/asset/loan/approve', async (req, res) => {
    const connection = await pool.getConnection();

    try {
        await connection.beginTransaction();

        const { loanId, approve, rejectReason, adminOpenid, adminName } = req.body;

        if (!loanId || approve === undefined) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        // 获取借用记录
        const [loans] = await connection.execute(
            'SELECT * FROM asset_loans WHERE id = ? AND status = "pending"',
            [loanId]
        );

        if (loans.length === 0) {
            await connection.rollback();
            return res.json({ code: 2001, success: false, message: '借用记录不存在或已处理' });
        }

        const loan = loans[0];
        const newStatus = approve ? 'approved' : 'rejected';

        // 更新借用记录
        await connection.execute(
            `UPDATE asset_loans 
             SET status = ?, approver_openid = ?, approver_name = ?, approve_time = NOW(), reject_reason = ?
             WHERE id = ?`,
            [newStatus, adminOpenid, adminName, rejectReason, loanId]
        );

        // 如果批准，更新资产状态
        if (approve) {
            await connection.execute(
                'UPDATE assets SET current_loan_id = ?, status = "in_use" WHERE id = ?',
                [loanId, loan.asset_id]
            );
        }

        await connection.commit();

        res.json({
            code: 0,
            success: true,
            message: approve ? '已批准' : '已拒绝'
        });
    } catch (error) {
        await connection.rollback();
        console.error('审批失败:', error);
        res.json({ code: 9999, success: false, message: '审批失败' });
    } finally {
        connection.release();
    }
});

// 归还资产
app.post('/api/asset/loan/return', async (req, res) => {
    const connection = await pool.getConnection();

    try {
        await connection.beginTransaction();

        const { loanId, condition, remark } = req.body;

        if (!loanId) {
            return res.json({ code: 1001, success: false, message: '缺少借用记录ID' });
        }

        // 获取借用记录
        const [loans] = await connection.execute(
            'SELECT * FROM asset_loans WHERE id = ? AND status IN ("approved", "overdue")',
            [loanId]
        );

        if (loans.length === 0) {
            await connection.rollback();
            return res.json({ code: 2001, success: false, message: '借用记录不存在或状态错误' });
        }

        const loan = loans[0];

        // 更新借用记录
        await connection.execute(
            `UPDATE asset_loans 
             SET status = 'returned', actual_return_date = NOW(), return_condition = ?, remark = CONCAT(IFNULL(remark, ''), '\n', ?)
             WHERE id = ?`,
            [condition, remark, loanId]
        );

        // 更新资产状态
        await connection.execute(
            'UPDATE assets SET current_loan_id = NULL, status = "in_use" WHERE id = ?',
            [loan.asset_id]
        );

        await connection.commit();

        res.json({ code: 0, success: true, message: '归还成功' });
    } catch (error) {
        await connection.rollback();
        console.error('归还失败:', error);
        res.json({ code: 9999, success: false, message: '归还失败' });
    } finally {
        connection.release();
    }
});

// 获取我的借用记录
app.get('/api/my-loans', async (req, res) => {
    try {
        const { openid, status, page = 1, pageSize = 20 } = req.query;

        if (!openid) {
            return res.json({ code: 1001, success: false, message: '缺少用户openid' });
        }

        let sql = `SELECT al.*, a.asset_code, a.name as asset_name, a.brand, a.model
                   FROM asset_loans al
                   LEFT JOIN assets a ON al.asset_id = a.id
                   WHERE al.borrower_openid = ?`;
        const params = [openid];

        if (status) {
            sql += ' AND al.status = ?';
            params.push(status);
        }

        sql += ' ORDER BY al.created_at DESC LIMIT ? OFFSET ?';
        params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize));

        const [rows] = await pool.execute(sql, params);

        res.json({ code: 0, success: true, data: { list: rows } });
    } catch (error) {
        console.error('获取我的借用记录失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 检查并更新逾期状态（可定时调用）
app.post('/api/admin/asset/loan/check-overdue', async (req, res) => {
    try {
        const { adminKey } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        // 更新逾期状态
        const [result] = await pool.execute(
            `UPDATE asset_loans 
             SET status = 'overdue'
             WHERE status = 'approved' 
             AND expected_return_date < CURDATE()`
        );

        res.json({
            code: 0,
            success: true,
            message: `已更新${result.affectedRows}条逾期记录`
        });
    } catch (error) {
        console.error('检查逾期失败:', error);
        res.json({ code: 9999, success: false, message: '检查失败' });
    }
});

// 生成资产二维码（简化版，返回资产链接）
app.post('/api/admin/asset/qrcode/generate', async (req, res) => {
    try {
        const { assetId, admin Key } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!assetId) {
            return res.json({ code: 1001, success: false, message: '缺少资产ID' });
        }

        // 生成二维码内容（小程序路径）
        const qrCodeContent = `pages/asset-detail/asset-detail?id=${assetId}`;

        // 更新资产的二维码字段
        await pool.execute(
            'UPDATE assets SET qr_code = ? WHERE id = ?',
            [qrCodeContent, assetId]
        );

        res.json({
            code: 0,
            success: true,
            data: {
                qrCodeContent,
                url: `https://你的域名/asset/${assetId}`
            }
        });
    } catch (error) {
        console.error('生成二维码失败:', error);
        res.json({ code: 9999, success: false, message: '生成失败' });
    }
});
